// CardSystem.cpp : Implementation of CCardSystem
#include "stdafx.h"
#include "CardSystem.h"


// CCardSystem

HRESULT CCardSystem::FinalConstruct()
{
	LONG lr = 0;
	DWORD cchReaders = SCARD_AUTOALLOCATE;

	HRESULT hres = CComObject<CReaders>::CreateInstance(&poReaders);
	if (hres == S_OK)
		poReaders->AddRef();

	if ((lr = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &poReaders->m_hCrdCtx) == SCARD_S_SUCCESS))
	{
		lr = SCardListReaders(poReaders->m_hCrdCtx, NULL, (LPTSTR)&poReaders->m_pmszReaders, &cchReaders);
	}
	_ASSERTE(lr == SCARD_S_SUCCESS);

	HRESULT hr = poReaders->QueryInterface(IID_IReaders, (void**)&m_spReaders);
	return hr;
}

void CCardSystem::FinalRelease()
{
	if (poReaders->m_pmszReaders)
		SCardFreeMemory(poReaders->m_hCrdCtx, poReaders->m_pmszReaders);

	if (poReaders->m_hCrdCtx)
		SCardReleaseContext(poReaders->m_hCrdCtx);

	poReaders->Release();
}

STDMETHODIMP CCardSystem::get_Readers(IReaders** pVal)
{
	_ASSERTE(pVal);
	(*pVal = m_spReaders)->AddRef();

	return S_OK;
}
